package cn.edu.ncut.cs.springboot.springsecuritydemo.controller;

import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.Role;
import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.User;
import cn.edu.ncut.cs.springboot.springsecuritydemo.service.SystemService;
import cn.edu.ncut.cs.springboot.springsecuritydemo.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/system")
@PreAuthorize("hasRole('ADMIN')")
public class SystemController {
    @Autowired
    private SystemService systemService;

    // 获取所有用户
    @GetMapping("/list")
    public JsonResult getAllUsers() {
        List<User> users = systemService.findAllUsers();
        return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "获取用户列表成功", users);
    }

    // 获取用户的角色
    @GetMapping("/{userId}/roles")
    public JsonResult getUserRoles(@PathVariable Long userId) {
        List<Role> roles = systemService.getRolesByUserId(userId);
        return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "获取用户角色成功", roles);
    }

    // 为用户分配角色
    @PostMapping("/{userId}/assignRoles")
    public JsonResult assignRolesToUser(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        boolean success = systemService.assignRolesToUser(userId, roleIds);
        if (success) {
            return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "角色分配成功", null);
        } else {
            return new JsonResult(JsonResult.JsonResultCode.ERROR, "角色分配失败", null);
        }
    }

    // 移除用户的角色
    @PostMapping("/{userId}/removeRoles")
    public JsonResult removeRolesFromUser(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        boolean success = systemService.removeRolesFromUser(userId, roleIds);
        if (success) {
            return new JsonResult(JsonResult.JsonResultCode.SUCCESS, "角色移除成功", null);
        } else {
            return new JsonResult(JsonResult.JsonResultCode.ERROR, "角色移除失败", null);
        }
    }
}
